<!--
   Copyright 2024 The Google Research Authors.
  
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
  
       http://www.apache.org/licenses/LICENSE-2.0
  
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->

<!DOCTYPE html>
<html>
<head>
<title>Click Button Sequence Click Widget Click Link Click Button Click Checkboxes Click Dialog Login User Task</title>
<!-- stylesheets -->
<link rel="stylesheet" type="text/css" href="../core/core.css">
<link rel="stylesheet" type="text/css" href="../core/jquery-ui/jquery-ui.min.css">
<style>
  #html { font-size: 10%; }
  .alink { text-decoration: underline; color: blue; cursor: pointer; }
  #area { height: 100px; display: block; }
  #dialog { height: auto !important; }
  .ui-dialog { font-size: 10px; }
  .ui-dialog .ui-dialog-titlebar { padding: 2px 3px; height: 15px; }
  .ui-button { outline: 0; }
  .ui-dialog .ui-dialog-content { padding: 0px; margin: 0 5px; }
  #subbtn { margin: 0 7px; }
  #area .widget { margin: 5px 0;}
  #area textarea { height: 20px; }
  #area input[type=input] { width: 120px !important; }
  #subbtn1 { width: 40px; height: 30px; }
  #subbtn2 { width: 40px; height: 30px; }
  .bold { font-weight: bold; }
  /* input { margin: 5px; width: 20px; }  */
  input[id="password"] { width: 120px; }
  input[id="username"] { width: 120px; }
  /* 160 + 160 + 160 + 160 + 160 + 50 + 50 + 50 */
  #wrap,
  #sync-task-cover {
    height: 950px;
    width: 160px;
  }

  #click-canvas,
  #reward-display {
    left: 165px;
  }

  #query {
    background-color: #FF0;
    font-size: 10px;
    height: 144px;
    padding: 3px;
  }
</style>

<!-- JS -->
<script src="../core/core.js"></script>
<script src="../core/d3.v3.min.js"></script>
<script src="../core/jquery-ui/external/jquery/jquery.js"></script>
<script src="../core/jquery-ui/jquery-ui.min.js"></script>
<script src="../common/ui_utils.js"></script>

<script>
core.EPISODE_MAX_TIME = 2000000;  // 2000 seconds

// click-button
var buttons = ['submit', 'okay', 'ok', 'yes', 'no', 'cancel', 'next', 'previous'];

// click-checkboxes
var createCheckboxes = function(div){
  var checkboxData = { toclick: {}, clickNames: [] };

  checkboxData.elems = core.randi(2, 7);
  for(var i=0;i<checkboxData.elems;i++) {
    var chname = ui_utils.generateString(2,8);
    var label = div.append('label')
    label.append('input').attr('type', 'checkbox').attr('id', 'ch'+i);
    label[0][0].innerHTML += chname;
    div.append('br');

    checkboxData.toclick[i] = false;
    if(core.randf(0,1) < 0.5) {
      checkboxData.toclick[i] = true;
      checkboxData.clickNames.push(chname);
    }
  }

  return checkboxData;
}

// click-option
var createElements = function(div){
  var n = core.randi(2, 7);
  var clickNames = [];
  for(var i=0;i<n;i++) {
    var chname = ui_utils.generateString(2,8);
    var label = div.append('label')
    label.append('input').attr('type', 'radio').attr('id', 'chop'+i).attr('name', 'radio');
    label[0][0].innerHTML += chname;
    div.append('br');
    clickNames.push(chname);
  }
  var ix = core.randi(0, n);
  var qstr = clickNames[ix];
  return {query: qstr, index: ix};
}

// click-dialog
var resetUI = function(div){
  if(div.html().length > 0) $('#dialog').dialog('destroy');
  div.empty(); // clear previous problem, if any
}

var createDialog = function(div){
  var html = '<p>' + ui_utils.generateWords(4,8) + '</p>';
  div.append(html);

  $('#dialog').dialog({ height: 70, position: {my: 'center', at: 'center', of: document.getElementById('area')} });

  $('.ui-dialog')[0].style.margin = core.randi(-10,20) + 'px ' + core.randi(5,25) + 'px';
  $('.ui-dialog')[0].style.width = core.randi(90,120) + 'px';
  $('.ui-dialog')[0].style.height = core.randi(70,100) + 'px';
}

// click-widget
var ELEMENT_NAMES = ['radio', 'checkbox', 'text', 'textarea', 'button'];
var ELEMENT_HTML = {
  'radio': {'start': '<div class="widget"><label><input type="radio" data-type="radio" name="radio">',
    'end': '</label></div>'},
  'checkbox': {'start':' <div class="widget"><label><input type="checkbox" data-type="checkbox">',
    'end':'</label></div>'},
  'text': {'start': '<div class="widget"><input type="input" data-type="text" value="',
    'end':'"></div>'},
  'textarea': {'start':'<div class="widget"><textarea data-type="textarea">',
    'end':'</textarea></div>'},
  'button': {'start': '<div class="widget"><button data-type="button">',
    'end':'</button></div>'}
};
var NUM_ELEMENTS = 5;


// click-link
// since we randomly generate links, run this in a while loop
// until we produce text that definitely contains a link,
// otherwise the script will error out and fail.
var createWidgetsLinks = function(div){
  // generate query text in the UI
  var elements = []
  var elements_html = []
  for(var i=0;i<NUM_ELEMENTS;i++){
    randIndex = core.randi(0,ELEMENT_NAMES.length);
    var elemName = ELEMENT_NAMES[randIndex];
    var randomText = ui_utils.generateString(1,6);
    elements_html.push(ELEMENT_HTML[elemName]['start'] + randomText + ELEMENT_HTML[elemName]['end']);
    elements.push(elemName);
  }
  var linkCreated = false;
  while(!linkCreated){
    var txt =  ui_utils.generateWords(20).split(/\s/g);
    for(var j=0;j<txt.length; j++){
      if(Math.random() < 0.2){
        txt[j] = '<span class="alink">' + txt[j] + '</span>';
        linkCreated = true;
      }
    }
  }
  div.html(elements_html.join(' ') + txt.join(' '));
  return [elements, txt];
}


var genProblem = function() {
  // click-dialog  
  var dialogDiv = $('#dialog');
  resetUI(dialogDiv);

  // click-button
  var div = d3.select('#area');
  div.html(''); // clear previous problem, if any

  var elementsWidgetsLinks = createWidgetsLinks(div);

  // click-button-sequence
  var button_seq_state = -1.0
  // var L = core.randi(0, 118); var U = core.randi(0, 118) + 50;
  var L = core.randi(40, 118); var U = core.randi(0, 30) + 150;
  div.append('button').attr('id', 'subbtn1').html('ONE');
  d3.select('#subbtn1').attr('style', 'position:absolute; left:'+L+'px; top:'+U+'px');
  d3.select('#subbtn1').on('click', function(){
    if (button_seq_state == -1.0) {
      button_seq_state = 1.0
    } else {
      button_seq_state = -2.0
    }
    console.log('click-button-sequence: ONE', button_seq_state);
  });

  // var L = core.randi(0, 118); var U = core.randi(0, 118) + 50;
  var L = core.randi(40, 118); var U = core.randi(0, 30) + 150;
  div.append('button').attr('id', 'subbtn2').html('TWO');
  d3.select('#subbtn2').attr('style', 'position:absolute; left:'+L+'px; top:'+U+'px');
  d3.select('#subbtn2').on('click', function(){
    if (button_seq_state == 1.0) {
      button_seq_state = 2.0
    } else {
      button_seq_state = -2.0
    }
    console.log('click-button-sequence: TWO', button_seq_state);
  });

  // click-widget
  var widget_state = -1.0;
  var widgetElements = elementsWidgetsLinks[0];
  var chosenElement = core.sample(widgetElements);
  $('#area .widget').on('click', function(){
    var elemType = $(this).find('input, textarea, button')[0].getAttribute('data-type');
    if (elemType === chosenElement) {
      widget_state = 1.0;
    } else {
      widget_state = -1.0;
    }
    console.log('click-widget', widget_state, button_seq_state);
  });

  // click-link  
  var correctText = elementsWidgetsLinks[1];
  var any = core.getOpt(core.QueryString, 'any', false); // click Any link?

  // click-button
  var num = 6;
  var elements = [];
  for(var i=0;i<num;i++) {
    var u = core.randf(0,1);
    var must_make_button = (i === num-1) && elements.length === 0;

    if(u < 0.33 && !must_make_button) {
      var txt = ''; for(var q=0;q<3;q++) { txt += ' ' + core.sample(ui_utils.lorem_words); }
      div.append('div').html(txt);
    } else if(u < 0.66 && !must_make_button) {

      if(core.randf(0,1) < 0.5) {
        var txt = ''; for(var q=0;q<3;q++) { txt += ' ' + core.sample(ui_utils.lorem_words); }
        txt += ': ';
        div.append('span').html(txt);
      }

      var w = core.randi(40, 150);
      div.append('input').attr('type', 'text').attr('style', 'width:' + w + 'px;');
      div.append('br');
    } else {
      var btn_text = core.sample(buttons);
      if(core.randf(0,1) < 0.5) btn_text = ui_utils.txtCapitalize(btn_text);
      var btn = div.append('button').html(btn_text);
      if(core.randf(0,1) < 0.5) div.append('br');
      elements.push(btn);
    }
  }

  // click-link
  var link_state = -1.0;
  var linkElements = document.getElementsByClassName('alink');
  var correctIndex = core.randi(0, linkElements.length);
  var correctText = linkElements[correctIndex].innerHTML;
  for(var i = 0, len = linkElements.length; i < len; i++) {
    var e = linkElements[i];
    if(e.innerHTML === correctText) {
      d3.select(e).on('click', function(){ link_state = 1.0; console.log('click-link', link_state, widget_state, button_seq_state ); })
    } else {
      d3.select(e).on('click', function(){ link_state = -1.0; console.log('click-link', link_state, widget_state, button_seq_state ); })
    }
  }

  // click-button
  var button_state = -1.0;
  var correct_text = core.sample(elements).html();  
  console.log([correct_text, elements.length]);
  for(var i = 0, len = elements.length; i < len; i++) {
    var e = elements[i];    
    console.log([e.html(), correct_text]);
    if(e.html() === correct_text) {
      e.on('click', function(){ console.log([e.html(), correct_text]); button_state = 1.0; console.log('click-button', button_state, link_state, widget_state, button_seq_state ); })
    } else {
      e.on('click', function(){ console.log([e.html(), correct_text]); button_state = -1.0; console.log('click-button', button_state, link_state, widget_state, button_seq_state ); })
    }
  }

  // click-checkboxes
  var box_state = -1.0;
  var div = d3.select('#area');
  var boxesDiv = $('#boxes');
  if (boxesDiv.length == 0){
    div.append('div').attr('id', 'boxes');
    div.append('br');
    div.append('button').attr('id', 'subbtn').attr('class', 'secondary-action').html('Submit');
  }

  var boxesDiv = d3.select('#boxes');
  var checkboxData = createCheckboxes(boxesDiv);

  var qstr = checkboxData.clickNames.join(', ');
  if(qstr.length === 0) { qstr = 'nothing'; }

  // click-option
  var option_state = -1.0;
  var correctElement = createElements(boxesDiv);

  d3.select('#subbtn').on('click', function(){
    var r = 0;
    for(var i=0;i<checkboxData.elems;i++) {
      var is_checked = d3.select('#ch'+i)[0][0].checked;
      r += is_checked === checkboxData.toclick[i] ? 1.0 : -1.0;
    }
    var checkboxes_r = r == checkboxData.elems ? 1.0 : -1.0;
    if (checkboxes_r == 1.0 && link_state == 1.0 && button_state == 1.0 && widget_state == 1.0 && button_seq_state == 2.0 ) {
      box_state = 1.0;
    } else {
      box_state = -1.0;
    }
    var option_r = d3.select('#chop'+correctElement.index)[0][0].checked ? 1.0 : -1.0;
    if (option_r == 1.0 && box_state == 1.0 && link_state == 1.0 && button_state == 1.0 && widget_state == 1.0 && button_seq_state == 2.0 ) {
      option_state = 1.0;
    } else {
      option_state = -1.0;
    }
    console.log('click-checkboxes and click-option', box_state, option_state, button_state, link_state, widget_state, button_seq_state );
  });

  // click-dialog 
  var dialog_state = -1.0;
  var dialogDiv = $('#dialog'); 
  if (dialogDiv.length == 0)  div.append('div').attr('id', 'dialog');
  var dialogDiv = $('#dialog');

  createDialog(dialogDiv);

  $('button.ui-button').on('click', function(){ 
    if (option_state == 1.0 && box_state == 1.0 && link_state == 1.0 && button_state == 1.0 && widget_state == 1.0 && button_seq_state == 2.0 ) {
      dialog_state = 1.0;
      console.log('click-dialog', dialog_state, option_state, box_state, option_state, button_state, link_state, widget_state, button_seq_state);
    } else {
      dialog_state = -1.0;
      console.log('click-dialog', dialog_state, option_state, box_state, option_state, button_state, link_state, widget_state, button_seq_state);
    }
  })

  // login-user
  div.append('div').attr('id', 'form');
  var form = d3.select('#form');
  form.html('<p><label class="bold">Username</label><input type="text" id="username"></p><p><label class="bold">Password</label><input type="password" id="password"></p><button id="subbtn3" class="secondary-action">Login</button>');
  d3.select('#username')[0][0].value ='';
  d3.select('#password')[0][0].value ='';

  var user = core.sample(ui_utils.FIFTY_NAMES).toLowerCase();
  var password = ui_utils.generateString(2,6)

  d3.select('#subbtn3').on('click', function(){
    var u = d3.select('#username')[0][0].value;
    var p = d3.select('#password')[0][0].value;
    var login_r = (u === user && p === password) ? 1.0 : -1.0;
    console.log('login-user', login_r, dialog_state, option_state, box_state, option_state, button_state, link_state, widget_state, button_seq_state);
    if (login_r == 1.0 && dialog_state == 1.0 && option_state == 1.0 && box_state == 1.0 && link_state == 1.0 && button_state == 1.0 && widget_state == 1.0 && button_seq_state == 2.0 ) {
      core.endEpisode(login_r, login_r > 0);
    } else {
      core.endEpisode(-1.0);
    }
  });

  // generate query text in the UI
  d3.select('#query').html('Click button ONE, then click button TWO, click on a "' + chosenElement + '" widget, click on the link "' + correctText + '", click on the "' + correct_text + '" button, select ' + qstr + ', select ' + correctElement.query + ' and click Submit, close the dialog box by clicking the "x", and then enter the <span class="bold">username</span> "' + user + '" and the <span class="bold">password</span> "' + password + '" into the text fields and press login.');
  // d3.select('#query').html('Select ' + qstr + ', select ' + correctElement.query + ' and click Submit, close the dialog box by clicking the "x", and enter the <span class="bold">username</span> "' + user + '" and the <span class="bold">password</span> "' + password + '" into the text fields and press login, after clicking button ONE, then clicking button TWO, clicking on a "' + chosenElement + '" widget, clicking on the link "' + correctText + '", and clicking on the "' + correct_text + '" button.');

}

window.onload = function() {
  core.startEpisode();
}
</script>
</head>
<!-- Base HTML -->
<body>
<div id="wrap">
  <div id="query"></div>
  <div id="area">
    <div id="boxes"></div>
    <div id='dialog'></div>
  </div>
</div>
</body>
</html>
